<?php

namespace backend\widgets\Chart;

use yii\base\Widget;
use yii\data\SqlDataProvider;
use yii\helpers\Json;

class SalesPlatformWidget extends Widget
{
    public $event_id;
    private $sales;

    public function init()
    {
        $this->sales = \Yii::$app->db->createCommand('
            SELECT SUM(`tariff`) as summ, COUNT(*) as count, `selling_platform`
            FROM `ticket_sales`
            WHERE `event_id`=:event_id
            GROUP BY `selling_platform`
        ', [':event_id' => $this->event_id])->queryAll();

        parent::init();
    }

    public function run()
    {   
        $this->registerPlugin();
        echo '<div>
              <canvas id="SellingPlatformChart"></canvas>
          </div>';
    }

    protected function registerPlugin()
    {

        $view = $this->getView();

        ChartAsset::register($view);
        
        $jsonSales = Json::encode($this->sales);

        $view->registerJs("
            const salesPlatformCanvas = document.getElementById('SellingPlatformChart');
            const dataSellingPlatformSales = " . $jsonSales . ";

            for(i = 0; i < dataSellingPlatformSales.length; i++)
            {
                if(dataSellingPlatformSales[i].selling_platform == 'kassir_orenburg_agent') 
                {
                    dataSellingPlatformSales[i].selling_platform = 'Сайт КассирРу';
                }
                if(dataSellingPlatformSales[i].selling_platform == 'widget_oren_mobileapp') 
                {
                    dataSellingPlatformSales[i].selling_platform = 'Мобильное приложение КассирРу';
                }
                if(dataSellingPlatformSales[i].selling_platform == 'widget-orenburg-ogikm') 
                {
                    dataSellingPlatformSales[i].selling_platform = 'Сайт музея';
                }
                if(dataSellingPlatformSales[i].selling_platform == 'офлайн касса музея') 
                {
                    dataSellingPlatformSales[i].selling_platform = 'Касса музея';
                }
            }
            new Chart(salesPlatformCanvas, {
                type: 'pie',
                data: {
                    labels: dataSellingPlatformSales.map(row => row.selling_platform),
                    datasets: [{
                        label: 'Количество билетов',
                        data: dataSellingPlatformSales.map(row => row.count),
                        borderWidth: 1
                    }]
                  },
                options: {
                    responsive: true,
                    plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: 'Распределение платформ продаж'
                    }
                    }
                },
            });");
        }


}
